from base import ApiBase
from error_code import Error

class Baidufanyi(ApiBase):
    """
    本类实现对百度翻译api的交互实现，包括请求，数据拆分，数据处理，错误处理依赖 error_code.Error() 具体功能
    """
    def __init__(self, app_id: str, api_key: str ,text: str):
        super().__init__()
        self.logging.getLogger(__name__)
        self.url = 'https://fanyi-api.baidu.com/api/trans/vip/translate'
        self.appid = app_id
        self.apikey = api_key
        self.text = text
        self.params = None
        self.logging.info('百度翻译初始化完成')

    def get_params(self):
        """拼接请求参数"""
        salt = self.random.randint(384933, 859438)
        sign = self.appid + self.text + str(salt) + self.apikey
        sign = self.hashlib.md5(sign.encode('utf-8')).hexdigest()
        self.params = {
            'q': self.text,
            'from': 'en',
            'to': 'zh',
            'appid': self.appid,
            'salt': salt,
            'sign': sign
        }
        self.logging.info('参数拼接完成')

    def get_response(self):
        try:
            self.get_params()
            response = self.requests.get(self.url, params=self.params,timeout=3)
            response.raise_for_status()
            self.data = response.json()
            return self.baidu_data() #返回数据处理
        except self.requests.exceptions.RequestException as err:
            self.logging.critical(f'请求型错误:{err}')

    def baidu_data(self):
        datas = []
        if self.data is None:
            return None, self.logging.error('回传参数为空')
        if 'error_code' in self.data:
            Error().code = self.data['error_code']  # 错误码处理
        elif 'trans_result' in self.data:
            self.logging.info('处理回传参数')
            data = {'zh': self.data['trans_result'][0]['dst'], 'en': self.data['trans_result'][0]['src']}
            # logging.info('完成处理')
            # return data
            datas.append(data)
            self.logging.info('完成处理')
            return datas

def main():
    appid = input('请输入appid:')
    apikey = input('请输入apikey:')
    data = 'hello world'
    baidufanyi = Baidufanyi(appid, apikey, data)
    data = baidufanyi.get_response()
    print(data)

if __name__ == '__main__':
    main()